package keygen.demo;

import java.security.NoSuchAlgorithmException;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;

import com.sun.crypto.provider.SunJCE;

public class testdes {

	public static void main(String[] args) {
		testdes my = new testdes();
		my.run();
	}

	public void run() {
		// 添加新安全算法 , 如果用 JCE 就要把它添加进去
		Security.addProvider(new SunJCE());
		String Algorithm = "DES"; // 定义 加密算法 , 可用 DES,DESede,Blowfish
		String myinfo = "WD-WXG1A70T4536";
		try {
			// 生成密钥
			KeyGenerator keygen = KeyGenerator.getInstance(Algorithm);
			SecretKey deskey = keygen.generateKey();
			// 加密
			// System.out.println("加密前的二进串 :" + byte2hex(myinfo.getBytes()));
			System.out.println("加密前的信息 :" + myinfo);
			Cipher c1 = Cipher.getInstance(Algorithm);
			c1.init(Cipher.ENCRYPT_MODE, deskey);
			byte[] cipherByte = c1.doFinal(myinfo.getBytes());
			System.out.println("加密后的二进串 :" + byte2hex(cipherByte));
			String keycode = byte2hex(cipherByte);
			// 解密
			c1 = Cipher.getInstance(Algorithm);
			c1.init(Cipher.DECRYPT_MODE, deskey);
			// byte[] clearByte = c1.doFinal(cipherByte);
			byte[] clearByte = c1.doFinal(hex2byte(keycode));
			System.out.println("解密后的二进串 :" + byte2hex(clearByte));
			System.out.println("解密后的信息 :" + (new String(clearByte)));
		} catch (NoSuchAlgorithmException e1) {
			e1.printStackTrace();
		} catch (NoSuchPaddingException e2) {
			e2.printStackTrace();
		} catch (Exception e3) {
			e3.printStackTrace();
		}
	}

	// 字节码转换成16进制字符串
	private static String byte2hex(byte bytes[]) {
		StringBuffer retString = new StringBuffer();
		for (int i = 0; i < bytes.length; ++i) {
			retString.append(Integer.toHexString(0x0100 + (bytes[i] & 0x00FF))
					.substring(1).toUpperCase());
		}
		return retString.toString();
	}

	// 将16进制字符串转换成字节码
	private static byte[] hex2byte(String hex) {
		byte[] bts = new byte[hex.length() / 2];
		for (int i = 0; i < bts.length; i++) {
			bts[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2),
					16);
		}
		return bts;
	}
}